#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
typedef pair<int, int> pii;
const int N = 1010;
int n, m;
int a[N][N];
int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
int st[N][N];
bool bfs(int mid)
{
    if (n == 1)
        return true;
    memset(st, 0, sizeof(st));
    queue<pii> as;
    for (int j = 1; j <= m; j++)
    {
        as.push({ 1,j });
        st[1][j] = 1;
    }
    while (as.size())
    {
        auto e = as.front();
        as.pop();
        int x1 = e.first;
        int y1 = e.second;
        for (int k = 0; k < 4; k++)
        {
            int x = x1 + dx[k];
            int y = y1 + dy[k];
            if (x >= 1 && x <= n && y >= 1 && y <= m && a[x][y] <= mid && st[x][y] == 0)
            {
                st[x][y] = 1;
                as.push({ x,y });
                if (x == n)
                {
                    return true;
                }
            }
        }
    }
    return false;

}
int main()
{
    int l = 0;
    int r = 0;
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            cin >> a[i][j];
            r = max(r, a[i][j]);
        }
    }
    while (l < r)
    {
        int mid = (l + r) / 2;
        if (bfs(mid))
        {
            r = mid;
        }
        else
        {
            l = mid + 1;
        }
    }
    cout << l << endl;
    return 0;
}